package com.Base;

import com.Login.Service.LoginService;
import com.Pojo.User;
import com.Utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * Created by XingYang on 2019/3/8.
 */
public class InitTool implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    LoginService loginService;
    RedisUtil redisUtil  = new RedisUtil();
    Jedis jedis = redisUtil.getClient();
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //将所有用户信息存入redis
        if(event.getApplicationContext().getParent()==null){
            if(loginService!=null){
                List<User> list = loginService.getAllUser();
                //清空redis缓存数据
                    jedis.flushAll();
                    List<String> roles = new ArrayList<>();
                    List<String> powers = new ArrayList<>();
                    LinkedHashSet<String> powerSet = new LinkedHashSet<>();

                for (User user:list){
                    roles = loginService.getRolesByUid(user.getId());
                    powerSet.addAll(loginService.getPowersByUid(user.getId()));
                    for(String role:roles){
                        powerSet.addAll(loginService.getPowersByRid(role));
                    }
                    user.setRoles(roles);
                    powers.addAll(powerSet);
                    user.setPowers(powers);
                    jedis.lpush(user.getUsername().getBytes(),redisUtil.serializeObj(user));
                    roles.clear();
                    powers.clear();
                    powerSet.clear();
                    System.out.println(user.toString());
                }
                jedis.close();
                System.out.println("用户初始化完成");
            }else{
                System.out.println("初始化失败！");
            }
        }



    }



}
